package model

import (
	"errors"
	"haodayizhi/global"

	"gorm.io/gorm"
)

const TableNameRoute = "routes"

// Route mapped from table <routes>
type Route struct {
	ID        int64  `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id,string"`
	Path      string `gorm:"column:path;type:varchar(255)" json:"path"`
	Component string `gorm:"column:component;type:varchar(255)" json:"component"`
	Name      string `gorm:"column:name;type:varchar(255)" json:"name"`
	Meta      string `gorm:"column:meta;type:json" json:"meta"`
	ParentID  int64  `gorm:"column:parent_id;type:bigint" json:"parentId"`
	Level     int64  `gorm:"column:level;type:int;default:1" json:"level"`
}

// TableName Route's table name
func (*Route) TableName() string {
	return TableNameRoute
}

// CreateRoute creates a new Route in the database.
func (m *Route) CreateRoute() error {
	if err := global.Db.Create(m).Error; err != nil {
		return err
	}
	return nil
}

// GetRouteByID retrieves a Route by its ID from the database.
func (m *Route) GetRouteByID(id int64) (*Route, error) {
	result := global.Db.First(m, id)
	if result.Error != nil {
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			return nil, nil // Route not found
		}
		return nil, result.Error
	}
	return m, nil
}

// UpdateRoute updates an existing Route in the database.
func (m *Route) UpdateRoute() error {
	if err := global.Db.Save(m).Error; err != nil {
		return err
	}
	return nil
}

// DeleteRoute deletes a Route by its ID from the database.
func (m *Route) DeleteRoute(id int64) error {
	if err := global.Db.Delete(m, id).Error; err != nil {
		return err
	}
	return nil
}
